﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Heyo.Class.Helper;
using static Heyo.Class.Helper.ImageHelper;
using Image = System.Windows.Controls.Image;

namespace Heyo.Controls
{
    public class BackgroundImage:Image
    {
        public static readonly DependencyProperty BlurRadiusProperty = DependencyProperty.Register(
            "BlurRadius", typeof(int), typeof(BackgroundImage), new PropertyMetadata(default(int)
            ));
        
        public int BlurRadius
        {
            get => (int) GetValue(BlurRadiusProperty);
            set => SetValue(BlurRadiusProperty, value);
        }

        public static readonly DependencyProperty BackgroundImageUriProperty = DependencyProperty.Register(
            "BackgroundImageUri", typeof(Uri), typeof(BackgroundImage), new PropertyMetadata(default(Uri),
                (s,e) =>
                {
                    ((BackgroundImage)s).ApplyBlur();
                }));

        public Uri BackgroundImageUri
        {
            get => (Uri) GetValue(BackgroundImageUriProperty);
            set => SetValue(BackgroundImageUriProperty, value);
        }

        public BackgroundImage()
        {
            Stretch = Stretch.UniformToFill;
        }

        private void ApplyBlur()
        {
            if (BlurRadius == 0)
            {
                Source = new BitmapImage(BackgroundImageUri);
                return;
            }

            Bitmap image = new BitmapImage(BackgroundImageUri).ToBitmap();

            if (image == null)
            {
                Source = null;
                return;
            }

            double imgWidth = Math.Min(image.Width, 1920);
            double imgHeight = (image.Height * (imgWidth / image.Width));
            Bitmap small=new Bitmap((int)imgWidth / 10, (int)imgHeight/10);
            Graphics graphics=Graphics.FromImage(small);
            graphics.DrawImage(image, 0,0, (int)imgWidth / 10, (int)imgHeight / 10);
            graphics.Dispose();
            GaussianBlur blur=new GaussianBlur(BlurRadius);
            Source = blur.ProcessImage(small).ToBitmapSource();
            image.Dispose();
            small.Dispose();
        }
    }
}
